﻿/**
 * Author:chzhcpu@gmail.com
 *  
*/

using System;
using System.Collections.Generic;
using System.Web;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using System.IO;

/// <summary>
	/// 任务事件的委托接口
	/// </summary>
	public delegate void TaskEventHandler( object sender, TaskEventArgs e ); 

/// <summary>
///cnPatentGrabber 的摘要说明
/// </summary>
public class cnPatentGrabber:Task
{

    private string pn = "";
    public cnPatentGrabber(string pn = "CN101671331"):base()
	{
		//
		//TODO: 在此处添加构造函数逻辑
        this.pn = pn;
	}

    public override void SearchbyPN(Object stateInfo)
    {
        string pnpath = AppDomain.CurrentDomain.BaseDirectory+"PatentFiles\\"+pn+"\\";

        string imghost = "http://211.157.104.86/";
        string shost = "http://211.157.104.87:8080/sipo/zljs/hyjs-jieguo.jsp";
        string detailhost = "http://211.157.104.87:8080/sipo/zljs/";
        string postpattern = "recshu=20&searchword=%B9%AB%BF%AA%A3%A8%B9%AB%B8%E6%A3%A9%BA%C5%3D%28%27@%25%27%29+&flag3=1&pg=1&sign=0&textfield5=@";
        string postdata = postpattern.Replace("@", pn);
        
        string prog = "";
        if (File.Exists(pnpath + pn + ".pdf"))
        {
            this.FireProgressChangedEvent(pn, "完成进度：100%");
            return;
        }

        if (!Directory.Exists(pnpath))
        {
            Directory.CreateDirectory(pnpath);
        }

        try
        {
            string shtml = UtilsList.PostHtmlPage(shost, postdata);
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(shtml);
            HtmlNode titlenode = doc.DocumentNode.SelectSingleNode("//td[@class='dixian1'][@width=542]/a");
            string detailurl = detailhost + titlenode.GetAttributeValue("href", "#");
            string dhtml = UtilsList.GetHtmlPage(detailurl);
            doc.LoadHtml(dhtml);
            titlenode = doc.DocumentNode.SelectSingleNode("//div[@class='q_list_3']/ul/li/a");
            string jsurl = titlenode.GetAttributeValue("onclick", "#");
            MatchCollection ms = Regex.Matches(jsurl, "'(.*?)'");
            int imgnum = Int16.Parse(ms[1].Groups[1].Value);
            string imgurl = imghost + ms[2].Groups[1].Value;

            //删除最后一个文件，以防下载不完整
            UtilsList.DeleteLatestFile(pnpath);

            //下载所有的tif文件
                       
            //UtilsList.DownloadFile(pnpath + pn + 1 + ".tif", imgurl);

            for (int i = 1; i <= imgnum; i++)
            {
                string tmp = string.Format("{0:D6}.tif", i);
                string durl = imgurl.Replace("000001.tif", tmp);

                if (File.Exists(pnpath + pn + i + ".tif"))
                {
                    continue;
                    /*
                     * 采用比较文件长度的办法判断文件完整性
                    if (UtilsList.GetLocalFileLength(pnpath + pn + i + ".tif")
                        < UtilsList.GetRemoteFileLength(durl))
                        continue;
                    else
                    {
                        File.Delete(pnpath + pn + i + ".tif");
                        UtilsList.DownloadFile(pnpath + pn + i + ".tif", durl);
                    }*/
                }
                else
                    UtilsList.DownloadFile(pnpath + pn + i + ".tif", durl);
                
                this.FireProgressChangedEvent(pn, "下载进度：" + ((i+0.0) / imgnum*100).ToString("F1")+"%");
            }

            if (!File.Exists(pnpath + pn + ".pdf"))
            {
                PDFGenetor.ImgtoPdf(pnpath + pn + ".pdf", pnpath);
            }
            prog = "完成进度：100%";
            
       }
        catch (Exception ex)
        {
            prog = ex.Message;
            //throw ex;
        }
        this.FireProgressChangedEvent(pn, prog);

        return ;
    }

}
